﻿using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using LockCrypt.Core;
using LockCrypt.DAL;

namespace LockCrypt.Mobile {
    /// <summary>
    /// A form to change program options.
    /// </summary>
    public partial class FrmOptions : Form {
        private bool closeAllowed = false;
        
        /// <summary>
        /// Initializes a new options form.
        /// </summary>
        public FrmOptions() {
            InitializeComponent();

            #region Data Binding
            txtDBLocation.Text = DalConfigurationManager.Provider.FileName;
            // Language dropdown
            foreach(var lang in Constants.Languages) {
                ddLanguage.Items.Add(lang.Value);
            }
            ddLanguage.SelectedItem = Constants.Languages[CoreConfigurationManager.Language];
            if(ddLanguage.SelectedIndex < 0) {
                ddLanguage.SelectedIndex = 0;
            }
            // Password boxes
            // removed 2009-12-12
            txtPassword.Text = DalConfigurationManager.Provider.Encryption.EncryptionKey;
            //txtPassword.Text = settings.Password;
            //txtConfirmPassword.Text = settings.Password;
            #endregion

            btnBrowse.Click += (s, e) => {
                FileInfo dbFile = new FileInfo(DalConfigurationManager.Provider.FileName);
                var dlg = new Lime49.Mobile.UI.OpenFileDialog(dbFile.DirectoryName, dbFile.Name);
                dlg.Filter = "*.lce";
                dlg.ShowDirectory(dbFile.DirectoryName);
                if(dlg.ShowDialog() == DialogResult.OK) {
                    txtDBLocation.Text = dlg.SelectedFile;
                }
            };
            itmCancel.Click += (s, e) => {
                closeAllowed = true;
                this.DialogResult = DialogResult.Cancel;
            };
            itmSave.Click += (s, e) => {
                closeAllowed = true;
                SavePreferences();
            };
            this.Closing += delegate(object sender, CancelEventArgs e) {
                if(!closeAllowed) {
                    DialogResult action = MessageBox.Show(I18nUtils.GetString("Strings", "PromptSaveSettingsDesc"), I18nUtils.GetString("Strings", "SaveChanges"), MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                    switch(action) {
                        case DialogResult.Cancel:
                            e.Cancel = true;
                            break;
                        case DialogResult.Yes:
                            SavePreferences();
                            break;
                    }
                }
            };
        }

        /// <summary>
        /// Save the entered preferences back to the Settings object.
        /// </summary>
        private void SavePreferences() {
            if(ValidateSettings()) {
                IDbProvider newProvider = DalConfigurationManager.Provider;
                newProvider.FileName = txtDBLocation.Text;
                if(newProvider.Encryption.EncryptionKey != txtPassword.Text) {
                    newProvider.ChangePassword(txtPassword.Text);
                }
                WinMobileConfigurationManager config = new WinMobileConfigurationManager() {
                     Language = Constants.Languages.First(l=>l.Value == ddLanguage.SelectedItem.ToString()).Key,
                     Provider = newProvider
                };
                WinMobileConfigurationManager.SaveConfiguration(config);
                
                this.DialogResult = DialogResult.OK;
            }
        }

        /// <summary>
        /// Validates that the settings entered are valid.
        /// </summary>
        private bool ValidateSettings() {
            if(string.IsNullOrEmpty(txtDBLocation.Text)) {
                MessageBox.Show(I18nUtils.GetString("Errors", "FilenameRequired"), I18nUtils.GetString("Errors", "Error"), MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
                txtDBLocation.SelectAll();
                txtDBLocation.Focus();
                return false;
            } else if(DalConfigurationManager.Provider.Encryption.EncryptionKey != txtPassword.Text) {
                if(string.IsNullOrEmpty(txtPassword.Text) && string.IsNullOrEmpty(txtConfirmPassword.Text)) {
                    if(MessageBox.Show(I18nUtils.GetString("Errors", "PassBlankDesc"), I18nUtils.GetString("Errors", "PasswordBlank"), MessageBoxButtons.YesNo, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1) == DialogResult.Yes) {
                        return true;
                    } else {
                        return false;
                    }
                } else if(txtPassword.Text != txtConfirmPassword.Text) {
                    MessageBox.Show(I18nUtils.GetString("Errors", "PasswordsDontMatch"), I18nUtils.GetString("Errors", "Error"), MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
                    txtPassword.SelectAll();
                    txtPassword.Focus();
                    return false;
                }
            }
            return true;
        }

    }
}